package com.xinxin.base.interceptor;

import com.xinxin.base.util.legacy.CommonUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.NamedThreadLocal;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Slf4j
public class RequestInterceptor implements HandlerInterceptor {

    private NamedThreadLocal<Long> startTimeThreadLocal = new NamedThreadLocal<>("StopWatch-startTimed");

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        startTimeThreadLocal.set(System.currentTimeMillis());
        String token = null;

        String path = request.getMethod() + " " + request.getServletPath();
        String ip = CommonUtil.getIp(request);
        StringBuilder parameter = new StringBuilder();

        Map<String, String[]> parameterMap = request.getParameterMap();
        for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
            String key = entry.getKey();
            if ("key".equals(key)) {
                token = entry.getValue()[0];
            }

            for (String value : entry.getValue()) {
                if (parameter.length() > 0) {
                    parameter.append("&");
                }
                parameter.append(key).append("=").append(value);
            }
        }

        if (StringUtils.isBlank(token)) {
            token = request.getHeader("key");
        }
        request.setAttribute("key", token);

        String info = "\n" + Thread.currentThread() + "——Request IP: " + ip +
                "\n" + path +
                "\nParams: " + parameter.toString();
        log.info(info);

        String device = request.getHeader("device");
        String version = request.getHeader("version");
        String channelid = request.getHeader("channelid");

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        try {
            String info = "\n" + Thread.currentThread() + "——Cost: " + (System.currentTimeMillis() - startTimeThreadLocal.get());
            if (ex == null) {
                info += "\n[Completion] " + request.getRequestURI();
            } else {
                info += "\n[Error: " + ex.getMessage() + "] " + request.getRequestURI();
            }
            log.info(info);
        } catch (Exception e) {
            log.error(Thread.currentThread() + "——拦截器异常：", e);
        } finally {
            request.removeAttribute("key");
        }
    }
}
